package com.application.model.universidades.quevasaestudiar.manager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.application.model.RetrivierWeb;

public class RetrivierWebQueVas extends RetrivierWeb {

	protected ManagerQueVasEntity 	informacion;
	public RetrivierWebQueVas(ManagerQueVasEntity 	informacion) {
		this.informacion = informacion;
	}
	protected String superGetWebPageContent(String url, String beginPatter, String endPatter, String charset) {
		return super.getWebPageContent(url, beginPatter, endPatter, charset);
	}
	@Override
	public String getWebPageContent(String url, String beginPatter, String endPatter, String charset) {
		String out = "";
		DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet(url);

            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("Login form get: " + response.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }

            HttpPost httpost = new HttpPost(url);

            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            nvps.add(new BasicNameValuePair("usuario", "quevas@mailinator.com"));
            nvps.add(new BasicNameValuePair("contrasenia", "quevas"));

            httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

            response = httpclient.execute(httpost);
            entity = response.getEntity();

            System.out.println("Login form get: " + response.getStatusLine());
            EntityUtils.consume(entity);
            
            System.out.println("Post logon cookies:");
            cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
            
            
            HttpGet httpget2 = new HttpGet(url);
            HttpResponse response2 = httpclient.execute(httpget);
            
            String value = "";
    		BufferedReader in = null;
    		boolean begin = false;
    		// boolean end=false;
    		try {
    			
//    			URL webPage = new URL("http://www.quevasaestudiar.com/carrera--Violoncelo-4974.html");
//    			URLConnection yc = webPage.openConnection();
//    			in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"utf-8"));
//    			in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"iso-8859-1"));
    			in = new BufferedReader(new InputStreamReader(response2.getEntity().getContent(),"utf-8"));
//    			in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    			String inputLine;
    			while ((inputLine = in.readLine()) != null) {
    				if (endPatter != null && inputLine.contains(endPatter)) {
    					break;
    				}
    				if (beginPatter == null || inputLine.contains(beginPatter)) {
    					begin = true;
    				}
    				if (begin) {
    					out += inputLine;
    				}
    			}
    			
    		} catch (Exception e) {
    			logger.error(e);
    		} finally {
    			if (in != null) {
    				try {
    					in.close();
    				} catch (IOException e) {
    					logger.error(e);
    				}
    			}
    		}
        } catch (Exception e) {
			logger.error(e);
		}finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
        return out;
	}
	@Override
	public void processContent(String data, String parentName) {
		

	}

	@Override
	public void retrieve() {
		

	}

	protected String getValue(String data,String regex,Integer grupoId){
		String		value = "";
		List<String>		values = null;
		values = getValues(data, regex, grupoId);
		if(!values.isEmpty()){
			value = values.get(0);
		}
		return value;
	}
	protected List<String> getValues(String data,String regex,Integer grupoId){
		List<String>		values = new LinkedList<String>();
		String value = "";
		Pattern     pattern = null;
        Matcher     matcher = null;
        pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
        matcher = pattern.matcher(data);
        
        while (matcher.find()) {
        	value = matcher.group(grupoId);
        	if(!values.contains(value)){
        		values.add(value);
        	}
        }
		return values;
	}
}
